﻿# -*- coding:utf-8 -*-
import json

from django.core.serializers.json import DjangoJSONEncoder
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from apitest.models import Apitest, Apistep, Apis, ApisSuite, ApitestSuite
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

import pymysql

from .tasks import manual_apissuite_testcase, periodictask_task_method
from djcelery.models import PeriodicTask, CrontabSchedule, IntervalSchedule
from .tasks import manual_apis_testcase, manual_apitest_testcase, manual_apitestsuite_testcase,manual_apitest_testcase_dependent


# Create your views here.

# 登录
def login(request):
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            request.session['user'] = username
            return HttpResponseRedirect('/index/')
        else:
            return render(request, 'login.html', {'error': 'username or password error'})
    return render(request, 'login.html')


@login_required
def index(request):
    username = request.session.get('user', '')  # 读取浏览器登录session
    if username == '':
        return HttpResponseRedirect('/index/')
    return render(request, "index.html", {"user": username})


@login_required
def logout(request):
    auth.logout(request)
    request.session.delete()  # 删除所有当前请求相关的session
    return HttpResponseRedirect('/login/')


# 分页功能
def pagination(req, datalist, datalist_size, alldatalist_size):
    page = req.GET.get("page", 1)  # 获取当前的页码数,默认为第1页
    rows = req.GET.get("rows", 10)
    paginator = Paginator(datalist, rows)  # 生成paginator对象,设置每页显示10条记录
    ret_rows = int(rows)
    try:
        ret_apilist = paginator.page(page)  # 获取当前页码数的记录列表
        # 精确查询的数据条数小于全量查询的数据条数，使用精确查询的数据条数
        if datalist_size < alldatalist_size:
            ret_rows = datalist_size
        # 精确查询的数据条数大于等于全量查询的数据条数，使用全量查询的数据条数
        if datalist_size >= alldatalist_size:
            ret_rows = alldatalist_size
    except PageNotAnInteger:
        ret_apilist = paginator.page(1)  # 如果输入的页数不是整数则显示第1页的内容
    except EmptyPage:
        ret_apilist = paginator.page(paginator.num_pages)  # 如果输入的页数不在系统的页数中则显示最后一页的内容
    return ret_apilist, ret_rows


# 流程接口管理页面
@login_required
def apitest_manage(request):
    username = request.session.get('user', '')  # 读取浏览器登录session
    apitestid = request.GET.get('suiteId')
    caseName = request.GET.get('caseName')
    return render(request, "apitest_manage.html",
                  {"user": username, "apitestid": apitestid, "caseName": caseName})  # 把值赋给apitestcounts这个变量


# 流程接口管理列表展示
@login_required
def apitest_manage_search(request):
    apitest_list, apitest_count = apitest_search(request)  # 流程接口搜索功能
    # rows为具体数据
    rows = []
    if len(apitest_list) != 0:
        for apitest in apitest_list:
            rows.append(
                {"id": apitest.id, "apitestnanme": apitest.apitestname, "apitestdesc": apitest.apitestdesc,
                 "apidependent": apitest.apidependent, "apitestresult": apitest.apitestresult,
                 "apitester": apitest.apitester, "create_time": apitest.create_time,
                 "update_time": apitest.update_time})
    response_data = {'total': apitest_count, 'rows': rows}
    return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type='application/json')


# 流程接口手工发送请求功能
@login_required
def manual_req_processInterface(request):
    """人工执行，前、后端所需要的字段：id（流程接口的id）,"""
    apitest_id = request.POST.get('id_id')
    apitest_apidependent = request.POST.get('apidependent')
    ret_dict = {}
    if apitest_apidependent == 'false':
        ret_dict = manual_apitest_testcase(apitest_id)  # 调手工执行流程接口
    elif apitest_apidependent == 'true':
        # todo 接口间依赖，待实现
        print("接口间依赖，待实现")
        ret_dict = manual_apitest_testcase_dependent(apitest_id)
    return HttpResponse(json.dumps(ret_dict), content_type='application/json')



# 接口步聚管理页面
@login_required
def apistep_manage(request):
    username = request.session.get('user', '')
    apitestid = request.GET.get('apitest.id', None)
    apitest = Apitest.objects.get(id=apitestid)  # 获取所有接口测试用例
    apistep_list = Apistep.objects.all().order_by('id')
    return render(request, "apistep_manage.html", {"user": username, "apitest": apitest, "apisteps": apistep_list})


# 单一接口suite页面
@login_required
def apis_suite(request):
    username = request.session.get('user', '')
    if username == '':
        return HttpResponseRedirect('/login/')
    return render(request, "apis_suite.html", {"user": username})


# 单一接口suite列表展示
@login_required
def apis_suite_list(request):
    apis_suite_list, apis_suite_count = apissuite_search(request)  # 单一接口suite搜索功能
    apis_suite_list_len = len(apis_suite_list)
    # rows为具体数据
    rows = []
    if apis_suite_list_len != 0:
        for apis_suite in apis_suite_list:
            rows.append(
                {"id": apis_suite.id, "productname": apis_suite.Product.productname,
                 "productdesc": apis_suite.Product.productdesc,
                 "case_name": apis_suite.case_name, "tester": apis_suite.tester, "create_time": apis_suite.create_time,
                 "update_time": apis_suite.update_time})
    response_data = {'total': apis_suite_count, 'rows': rows}
    return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type='application/json')


# 单一接口suite搜索功能
def apissuite_search(request):
    search_product = request.GET.get("search_product", "")  # 获取Product产品
    search_tester = request.GET.get("search_tester", "")  # 获取tester测试人
    search_start_date = request.GET.get("search_datetimestart", "")  # 获取datetimeStart创建开始日期
    search_end_date = request.GET.get("search_datetimeend", "")  # 获取datetimeEnd创建结束日期

    apis_suite_search_list = []
    # 查询产品，负责人，结果均为空，根据id查出全量数据
    if search_product == "" and search_tester == "" and search_start_date == "" and search_end_date == "":
        apis_suite_search_list = ApisSuite.objects.all().order_by('id')
    else:
        # 查询产品，测试人，创建日期，均不为空，查询出交集数据
        if search_product != "" and search_tester != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apis_suite_search_list = ApisSuite.objects.filter(Product__productname__icontains=search_product,
                                                              tester__exact=search_tester,
                                                              create_time__range=(search_start_date, search_end_date))
        # 查询产品，测试人
        elif search_product != "" and search_tester != "":
            apis_suite_search_list = ApisSuite.objects.filter(Product__productname__icontains=search_product,
                                                              tester__exact=search_tester)
        # 查询产品，日期
        elif search_product != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apis_suite_search_list = ApisSuite.objects.filter(Product__productname__icontains=search_product,
                                                              create_time__range=(search_start_date, search_end_date))
        # 查询测试人，日期
        elif search_tester != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apis_suite_search_list = ApisSuite.objects.filter(tester__exact=search_tester,
                                                              create_time__range=(search_start_date, search_end_date))

        # 查询产品
        elif search_product != "":
            apis_suite_search_list = ApisSuite.objects.filter(Product__productname__icontains=search_product)
        # 查询测试人
        elif search_tester != "":
            apis_suite_search_list = ApisSuite.objects.filter(tester__exact=search_tester)
        # 查询日期
        elif search_start_date < search_end_date != "" and search_start_date != "":
            apis_suite_search_list = ApisSuite.objects.filter(create_time__range=(search_start_date, search_end_date))

    # 分页逻辑
    apis_suite_count = ApisSuite.objects.all().count()
    ret_apis_suite_search_list = []
    apis_suite_search_list_len = len(apis_suite_search_list)
    # 查到数据（数据条数不为0），进行分页
    if len(apis_suite_search_list) != 0:
        ret_apis_suite_search_list, apis_suite_count = pagination(request, apis_suite_search_list,
                                                                  apis_suite_search_list_len, apis_suite_count)
    return ret_apis_suite_search_list, apis_suite_count


# 单一接口管理
@login_required
def apis_manage(request):
    username = request.session.get('user', '')
    apisid = request.GET.get('suiteId')
    caseName = request.GET.get('caseName')
    return render(request, "apis_manage.html",
                  {"user": username, "apisid": apisid, "caseName": caseName})


# 单一接口管理列表展示
@login_required
def apis_manage_list(request):
    apis_list, apis_count = apis_search(request)  # 单一接口搜索功能

    # rows为具体数据
    rows = []
    # 查询回来有数据
    if len(apis_list) != 0:
        for apis in apis_list:
            rows.append(
                {"id": apis.id, "apiname": apis.apiname, "apiurl": apis.apiurl, "apiparamvalue": apis.apiparamvalue,
                 "apimethod": apis.apimethod, "apiresult": apis.apiresult, "apistatus": apis.apistatus,
                 "apitester": apis.apitester, "create_time": apis.create_time, "update_time": apis.update_time})
    response_data = {'total': apis_count, 'rows': rows}
    return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type='application/json')


# 单一接口suite手工发送请求功能
@login_required
def manual_req_apissuite(request):
    """人工执行，前、后端所需要的字段：id"""
    apis_suiteid = request.POST.get('id_id')
    ret_dict = manual_apissuite_testcase(apis_suiteid)  # 调手工批量执行suite单一接口
    return HttpResponse(json.dumps(ret_dict), content_type='application/json')


# 单一接口手工发送请求功能
@login_required
def manual_req_singleInterface(request):
    """人工执行，前、后端所需要的字段：id"""
    apis_id = request.POST.get('id_id')
    ret = manual_apis_testcase(apis_id)  # 调手工执行单一接口
    return HttpResponse(json.dumps(ret), content_type='application/json')


# 单一接口搜索功能
def apis_search(request):
    search_caseName = request.GET.get("search_caseName", "")  # 获取用例名称/接口名称
    search_apitester = request.GET.get("search_apitester", "")  # 获取apitester负责人
    search_start_date = request.GET.get("search_datetimestart", "")  # 获取datetimeStart开始日期
    search_end_date = request.GET.get("search_datetimeend", "")  # 获取datetimeEnd结束日期
    search_selApis = request.GET.get("search_selApis", "")  # 获取selApis结果
    apisSuiteId = request.GET.get("search_apisSuite_id", "")  # 获取suiteId（用例集的编号）

    apis_search_list = []
    # 查询用例名称/接口名称，负责人，结果均为空，根据id查出全量数据
    if search_caseName == '' and search_apitester == '' and search_start_date == '' and search_end_date == '' and search_selApis == '':
        apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId).order_by('id')
    else:
        # 查询用例名称/接口名称，负责人，结果，创建日期，均不为空，查询出交集数据
        if search_caseName != '' and search_apitester != '' and search_selApis != '' and search_start_date < search_end_date != '' and search_start_date != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId,
                                                   Apis_case_name__icontains=search_caseName,
                                                   apitester__exact=search_apitester, apistatus__exact=search_selApis,
                                                   create_time__range=(search_start_date, search_end_date))
        # 查询用例名称/接口名称，负责人，结果
        elif search_caseName != '' and search_apitester != '' and search_selApis != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId,
                                                   Apis_case_name__icontains=search_caseName,
                                                   apitester__exact=search_apitester, apistatus__exact=search_selApis)
        # 查询用例名称/接口名称，负责人
        elif search_caseName != '' and search_apitester != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId,
                                                   Apis_case_name__icontains=search_caseName,
                                                   apitester__exact=search_apitester)
        # 查询用例名称/接口名称，结果
        elif search_caseName != '' and search_selApis != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId,
                                                   Apis_case_name__icontains=search_caseName,
                                                   apistatus__exact=search_selApis)
        # 查询用例名称/接口名称，日期
        elif search_caseName != '' and search_start_date < search_end_date != '' and search_start_date != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId,
                                                   Apis_case_name__icontains=search_caseName,
                                                   create_time__range=(search_start_date, search_end_date))
        # 查询负责人，日期
        elif search_apitester != '' and search_start_date < search_end_date != "" and search_start_date != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId, apitester__exact=search_apitester,
                                                   create_time__range=(search_start_date, search_end_date))
        # 查询负责人，结果
        elif search_apitester != '' and search_selApis != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId, apitester__exact=search_apitester,
                                                   apistatus__exact=search_selApis)
        # 查询结果，日期
        elif search_selApis != '' and search_start_date < search_end_date != '' and search_start_date != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId, apistatus__exact=search_selApis,
                                                   create_time__range=(search_start_date, search_end_date))
        # 查询用例名称/接口名称
        elif search_caseName != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId,
                                                   apiname__icontains=search_caseName)
        # 查询负责人
        elif search_apitester != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId, apitester__exact=search_apitester)
        # 查询结果
        elif search_selApis != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId, apistatus__exact=search_selApis)
        # 查询创建日期
        elif search_start_date < search_end_date != '' and search_start_date != '':
            apis_search_list = Apis.objects.filter(ApisSuite__id__exact=apisSuiteId,
                                                   create_time__range=(search_start_date, search_end_date))

    # 分页逻辑
    apis_count = Apis.objects.all().count()
    ret_apis_search_list = []
    apis_search_list_len = len(apis_search_list)
    # 查到数据（数据条数不为0），进行分页
    if len(apis_search_list) != 0:
        ret_apis_search_list, apis_count = pagination(request, apis_search_list,
                                                      apis_search_list_len, apis_count)
    return ret_apis_search_list, apis_count


# 流程接口suite页面
@login_required
def apitest_suite(request):
    username = request.session.get('user', '')
    if username == '':
        return HttpResponseRedirect('/login/')
    return render(request, "apitest_suite.html", {"user": username})


# 流程接口suite列表展示
@login_required
def apitest_suite_list(request):
    apitest_suite_list, apitest_suite_count = apitest_suite_search(request)  # 流程接口suite搜索功能

    # rows为具体数据
    rows = []
    # 查询回来有数据
    if len(apitest_suite_list) != 0:
        for apitest_suite in apitest_suite_list:
            rows.append(
                {"id": apitest_suite.id, "productname": apitest_suite.Product.productname,
                 "productdesc": apitest_suite.Product.productdesc,
                 "apitest_caseName": apitest_suite.apitest_caseName, "apitest_tester": apitest_suite.apitest_tester,
                 "create_time": apitest_suite.create_time,
                 "update_time": apitest_suite.update_time})
    response_data = {'total': apitest_suite_count, 'rows': rows}
    return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type='application/json')


# 流程接口suite搜索功能
def apitest_suite_search(request):
    search_product = request.GET.get("search_product", "")  # 获取Product产品
    search_tester = request.GET.get("search_tester", "")  # 获取tester测试人
    search_start_date = request.GET.get("search_datetimestart", "")  # 获取datetimeStart开始日期
    search_end_date = request.GET.get("search_datetimeend", "")  # 获取datetimeEnd结束日期

    apitest_suite_search_list = []
    # 查询产品，负责人，结果均为空，根据id查出全量数据
    if search_product == "" and search_tester == "" and search_start_date == "" and search_end_date == "":
        apitest_suite_search_list = ApitestSuite.objects.all().order_by('id')
    else:
        # 查询产品，测试人，日期，均不为空，查询出交集数据
        if search_product != "" and search_tester != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apitest_suite_search_list = ApitestSuite.objects.filter(Product__productname__icontains=search_product,
                                                                    apitest_tester__exact=search_tester,
                                                                    create_time__range=(
                                                                        search_start_date, search_end_date))
        # 查询产品，测试人
        elif search_product != "" and search_tester != "":
            apitest_suite_search_list = ApitestSuite.objects.filter(Product__productname__icontains=search_product,
                                                                    apitest_tester__exact=search_tester)
        # 查询产品，日期
        elif search_product != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apitest_suite_search_list = ApitestSuite.objects.filter(Product__productname__icontains=search_product,
                                                                    create_time__range=(
                                                                        search_start_date, search_end_date))
        # 查询测试人，日期
        elif search_tester != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apitest_suite_search_list = ApitestSuite.objects.filter(apitest_tester__exact=search_tester,
                                                                    create_time__range=(
                                                                        search_start_date, search_end_date))
        # 查询产品
        elif search_product != "":
            apitest_suite_search_list = ApitestSuite.objects.filter(Product__productname__icontains=search_product)
        # 查询测试人
        elif search_tester != "":
            apitest_suite_search_list = ApitestSuite.objects.filter(apitest_tester__exact=search_tester)
        # 查询日期
        elif search_start_date < search_end_date != "" and search_start_date != "":
            apitest_suite_search_list = ApitestSuite.objects.filter(
                create_time__range=(search_start_date, search_end_date))

    apitest_suite_count = ApitestSuite.objects.all().count()  # 统计产品数
    apitest_suite_search_list_len = len(apitest_suite_search_list)
    if apitest_suite_search_list_len != 0:
        ret_apitest_suite_search_list, apitest_suite_count = pagination(request, apitest_suite_search_list,
                                                                        apitest_suite_search_list_len,
                                                                        apitest_suite_count)
    return ret_apitest_suite_search_list, apitest_suite_count


# 流程接口suite手工发送请求功能
@login_required
def manual_req_apitestsuite(request):
    """人工执行，前、后端所需要的字段：id"""
    apitest_id = request.POST.get('id_id')
    ret = manual_apitestsuite_testcase(apitest_id)  # 调手工批量执行suite流程接口
    return HttpResponse(json.dumps(ret), content_type='application/json')


# 流程接口搜索功能
@login_required
def apitest_search(request):
    search_apitestcaseName = request.GET.get("search_apitestcaseName", "")  # 获取apitestcaseName用例名称
    search_apitester = request.GET.get("search_apitester", "")  # 获取apitester负责人
    search_start_date = request.GET.get("search_datetimestart", "")  # 获取datetimeStart开始日期
    search_end_date = request.GET.get("search_datetimeend", "")  # 获取datetimeEnd结束日期
    search_selApis = request.GET.get("search_selApis", "")  # 获取selApis结果
    search_apitestSuite_id = request.GET.get("search_apitestSuite_id", "")  # 获取search_apitestSuite_id结果

    apitest_search_list = []
    # 查询用例名称，负责人，结果均为空，根据id查出全量数据
    if search_apitestcaseName == "" and search_apitester == "" and search_start_date == "" and search_end_date == "" and search_selApis == "":
        apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id).order_by('id')
    else:
        # 查询用例名称，负责人，结果，日期，均不为空，查询出交集数据
        if search_apitestcaseName != "" and search_apitester != "" and search_selApis != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestname__icontains=search_apitestcaseName,
                                                         apitester__exact=search_apitester,
                                                         apitestresult__exact=search_selApis,
                                                         create_time__range=(search_start_date, search_end_date))
        # 查询用例名称，负责人，结果
        elif search_apitestcaseName != "" and search_apitester != "" and search_selApis != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestname__icontains=search_apitestcaseName,
                                                         apitester__exact=search_apitester,
                                                         apitestresult__exact=search_selApis)
        # 查询用例名称，负责人
        elif search_apitestcaseName != "" and search_apitester != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestname__icontains=search_apitestcaseName,
                                                         apitester__exact=search_apitester)
        # 查询用例名称，结果
        elif search_apitestcaseName != "" and search_selApis != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestname__icontains=search_apitestcaseName,
                                                         apitestresult__exact=search_selApis)
        # 查询用例名称，日期
        elif search_apitestcaseName != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestname__icontains=search_apitestcaseName,
                                                         create_time__range=(search_start_date, search_end_date))
        # 查询负责人，日期
        elif search_apitester != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitester__exact=search_apitester,
                                                         create_time__range=(search_start_date, search_end_date))
        # 查询负责人，结果
        elif search_apitester != "" and search_selApis != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitester__exact=search_apitester,
                                                         apistatus__exact=search_selApis)
        # 查询结果，日期
        elif search_selApis != "" and search_start_date < search_end_date != "" and search_start_date != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestresult__exact=search_selApis,
                                                         create_time__range=(search_start_date, search_end_date))
        # 查询用例名称
        elif search_apitestcaseName != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestname__icontains=search_apitestcaseName)
        # 查询负责人
        elif search_apitester != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitester__exact=search_apitester)
        # 查询结果
        elif search_selApis != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         apitestresult__exact=search_selApis)
        # 查询日期
        elif search_start_date < search_end_date != "" and search_start_date != "":
            apitest_search_list = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id,
                                                         create_time__range=(search_start_date, search_end_date))

    apitest_search_count = Apitest.objects.filter(ApitestSuite__id__exact=search_apitestSuite_id).order_by('id').count()
    apitest_search_list_len = len(apitest_search_list)
    if apitest_search_list_len != 0:
        ret_apitest_search_list, apitest_search_count = pagination(request, apitest_search_list,
                                                                   apitest_search_list_len, apitest_search_count)
    return ret_apitest_search_list, apitest_search_count


# 流程步骤搜索功能
@login_required
def apistep_search(request):
    username = request.session.get('user', '')  # 读取浏览器登录session
    search_apiname = request.GET.get("apiname", "")
    apistep_list = Apistep.objects.filter(apiname__icontains=search_apiname)
    return render(request, 'apistep_manage.html', {"user": username, "apisteps": apistep_list})


# 测试报告
@login_required
def bug_report(request):
    username = request.session.get('user', '')
    if username == '':
        return HttpResponseRedirect('/login/')

    apis_list = Apis.objects.all()
    apis_count = Apis.objects.all().count()  # 统计接口数
    db = pymysql.connect(user='root', db='autotest', passwd='root123456!@#$%^', host='127.0.0.1')
    cursor = db.cursor()
    sql1 = 'SELECT count(id) FROM apitest_apis WHERE apitest_apis.apistatus=1'
    aa = cursor.execute(sql1)
    apis_pass_count = [row[0] for row in cursor.fetchmany(aa)][0]
    sql2 = 'SELECT count(id) FROM apitest_apis WHERE apitest_apis.apistatus=0'
    bb = cursor.execute(sql2)
    apis_fail_count = [row[0] for row in cursor.fetchmany(bb)][0]
    db.close()
    return render(request, "report.html",
                  {"user": username, "apiss": apis_list, "apiscounts": apis_count, "apis_pass_counts": apis_pass_count,
                   "apis_fail_counts": apis_fail_count})  # 把值赋给apiscounts这个变量


# 测试报告
@login_required
def apitest_report(request):
    username = request.session.get('user', '')
    if username == '':
        return HttpResponseRedirect('/login/')
    return render(request, "apitest_report.html")


# 定时任务
@login_required()
def periodic_task(request):
    username = request.session.get('user', '')
    if username == '':
        return HttpResponseRedirect('/login/')
    return render(request, "periodic_task.html", {"user": username})


# 定时任务列表展示
@login_required
def periodic_task_list(request):
    task_list, periodic_list, crontab_list, task_count = periodictask_search(request)  # 定时任务的搜索功能

    # rows为具体数据
    rows = []
    if task_count != 0:
        for task in task_list:
            for periodic in periodic_list:
                if task.interval_id != '' and task.interval_id == periodic.id:
                    rows.append(
                        {"taskid": task.id, "taskname": task.name, "taskmodule": task.task,
                         "tasktimeplan": "每" + str(periodic.every) + str(periodic.period) + "次",
                         "taskcreatetime": task.create_date, "taskupdatetime": task.update_date,
                         "taskenabled": str(task.enabled)})
                break
            for crontab in crontab_list:
                if crontab.id != '' and task.crontab_id == crontab.id:
                    rows.append(
                        {"taskid": task.id, "taskname": task.name, "taskmodule": task.task,
                         "tasktimeplan": str(crontab.month_of_year) + "年" + str(crontab.day_of_month) + "月" + str(
                             crontab.day_of_week) + "日" + str(crontab.hour) + "时" + str(crontab.minute) + "分",
                         "taskcreatetime": task.create_date, "taskupdatetime": task.update_date,
                         "taskenabled": str(task.enabled)})
    response_data = {'total': task_count, 'rows': rows}
    return HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder), content_type='application/json')


# 搜索功能
def periodictask_search(request):
    search_taskname = request.GET.get("search_taskname", "")
    search_taskmodule = request.GET.get("search_taskmodule", "")
    search_seltaskenabled = request.GET.get("search_seltaskenabled", "")

    task_list = []
    if search_taskname == "" and search_taskmodule == "" and search_seltaskenabled == "":
        task_list = PeriodicTask.objects.all().order_by('id')
    else:
        if search_taskname != '' and search_taskmodule != '' and search_seltaskenabled != '':
            task_list = PeriodicTask.objects.filter(name__icontains=search_taskname, task__icontains=search_taskmodule,
                                                    enabled__exact=search_seltaskenabled)
        elif search_taskname != '' and search_taskmodule != '':
            task_list = PeriodicTask.objects.filter(name__icontains=search_taskname, task__icontains=search_taskmodule)
        elif search_taskname != '' and search_seltaskenabled != '':
            task_list = PeriodicTask.objects.filter(name__icontains=search_taskname,
                                                    enabled__exact=search_seltaskenabled)
        elif search_taskmodule != '' and search_seltaskenabled != '':
            task_list = PeriodicTask.objects.filter(task__icontains=search_taskmodule,
                                                    enabled__exact=search_seltaskenabled)
        elif search_taskname != '':
            task_list = PeriodicTask.objects.filter(name__icontains=search_taskname)
        elif search_taskmodule != '':
            task_list = PeriodicTask.objects.filter(task__icontains=search_taskmodule)
        elif search_seltaskenabled != '':
            task_list = PeriodicTask.objects.filter(enabled__exact=search_seltaskenabled)

    task_count = PeriodicTask.objects.all().count()
    task_list_len = len(task_list)
    if task_list_len != 0:
        ret_task_list, task_count = pagination(request, task_list, task_list_len, task_count)
    periodic_list = IntervalSchedule.objects.all().order_by('id')  # 周期任务 （如：每隔1小时执行1次）
    crontab_list = CrontabSchedule.objects.all().order_by('id')  # 定时任务 （如：某年月日的某时，每天的某时）
    return ret_task_list, periodic_list, crontab_list, task_count


# 手工执行任务
@login_required
def manual_periodictasks(request):
    periodictask_taskmodule = request.POST.get('taskmodule')
    ret_dict = periodictask_task_method(periodictask_taskmodule)
    return HttpResponse(json.dumps(ret_dict), content_type='application/json')
